import load from '@/utils/jsapi.js';
import maprenderer from '@/utils/maprenderer'
import SencelayerRenderer from '@/utils/SencelayerRenderer'
import JSON from 'json3';
import {
  Message,
  Tree
} from 'element-ui';
const mapoperation = {

  async goToPosition(Parameters) {
    const [
      Camera
    ] = await load([
      "esri/Camera"
    ]);
    const camera = new Camera({
      fov: Parameters.fov,
      heading: Parameters.heading,
      position: {
        x: Parameters.position.x,
        y: Parameters.position.y,
        z: Parameters.position.z,
        spatialReference: Parameters.position.spatialReference
      },
      tilt: Parameters.tilt
    });

    if (camera != null && Parameters.options != undefined) {
      window.sceneView.goTo(camera, Parameters.options)
    } else {
      window.sceneView.goTo(camera)
    }
  },

  //接口未开放
  toggleLayerVisbile(Parameters) {
    const toggleLayer = window.map.findLayerById(Parameters.layerName);
    if (toggleLayer != null || toggleLayer != undefined) {
      if (Parameters.Action.toUpperCase() === "SHOW") {
        toggleLayer.visible = true;
        toggleLayer.listMode = "show";
      } else if (Parameters.Action.toUpperCase() === "HIDE") {
        toggleLayer.visible = false;
        toggleLayer.listMode = "hide";
      } else {
        Message({
          message: "当前图层操作接口不存在",
          type: 'warning',
          duration: 2 * 1000
        })
      }
    } else {
      Message({
        message: "图层" + Parameters.layerName + "不存在",
        type: 'warning',
        duration: 2 * 1000
      })
    }
  },

  async setLayerVisible(Parameters) {
    const [Legend] = await load(["esri/widgets/Legend"]);
    const toggleLayer = window.map.findLayerById(Parameters.layerName);
    if (toggleLayer != null || toggleLayer != undefined) {
      if (Parameters.visible === true) {
        if (Parameters.definitionExpression) {
          toggleLayer.definitionExpression = Parameters.definitionExpression;
        }
        if (Parameters.sublayers != null && Parameters.sublayers != undefined) {
          window.currentSubLayerArray = Parameters.sublayers;
          toggleLayer.sublayers = Parameters.sublayers;


          if (Parameters.legendVisible != null && Parameters.legendVisible != undefined && Parameters.legendVisible == true) {
            let legendlayer = window.map.findLayerById(Parameters.layerName + "_legend");
            legendlayer.sublayers = Parameters.sublayers;
            legendlayer.visible = true;
            legendlayer.opacity = 1;
            legendlayer.listMode = "hide";
            legendlayer.sublayers.map(function (sublayer, index, ary) {
              sublayer.definitionExpression = "1=2";
            });
            if (window.legend != null) window.sceneView.ui.remove(window.legend);
            window.legend = new Legend({
              view: window.sceneView,
              layerInfos: [{
                layer: legendlayer,
              }]
            });
            window.sceneView.ui.add(window.legend, "bottom-left");
          } else {
            if (window.legend != null) window.sceneView.ui.remove(window.legend);
          }
        }
        toggleLayer.visible = true;
        toggleLayer.listMode = "show";
      } else if (Parameters.visible === false) {
        toggleLayer.visible = false;
        // toggleLayer.listMode = "hide";
      } else {
        Message({
          message: "当前图层操作接口不存在",
          type: 'warning',
          duration: 2 * 1000
        })
      }
    } else {
      Message({
        message: "图层" + Parameters.layerName + "不存在",
        type: 'warning',
        duration: 2 * 1000
      })
    }
  },

  mapthemechange(Parameters) {
    if (Parameters.mode == undefined || Parameters.mode == null) return;
    let layertheme;
    let modelayertheme;
    if (Parameters.mode == "dark") {
      layertheme = 'basemap_as'
      modelayertheme = 'model_white_as';
      window.map.ground.surfaceColor = '#021425'
      $('.calcite-map').removeClass("calcite-widgets-dark calcite-widgets-light").addClass("calcite-widgets-dark");
    } else if (Parameters.mode == "light") {
      layertheme = 'basemap_zw';
      modelayertheme = 'model_white_zw';
      window.map.ground.surfaceColor = '#EDEDED'
      $('.calcite-map').removeClass("calcite-widgets-dark calcite-widgets-light").addClass("calcite-widgets-light");
    } else {
      layertheme = 'basemap_air';
      modelayertheme = 'model_air_real';
      window.map.ground.surfaceColor = '#021425'
      $('.calcite-map').removeClass("calcite-widgets-dark calcite-widgets-light").addClass("calcite-widgets-dark");
    };

    window.map.basemap.baseLayers.items.forEach(function (item) {
      if (item.id === layertheme) {
        item.visible = true;
        // if (window.mapmodel === "2D") return;
        // ['model_white_as', 'model_white_zw', 'model_air_real'].forEach(element => {
        //   const layer = window.map.findLayerById(element);
        //   if (layer == null || layer == undefined) return
        //   if (modelayertheme == element) {
        //     layer.visible = item.visible;
        //     layer.listMode = item.listMode;
        //   }else{
        //        layer.visible = !item.visible;
        //        layer.listMode = !item.listMode;
        //   }
        // });
      } else {
        item.visible = false;
      }
    })
  },

  mapscenechange(Parameters) {
    if (Parameters.mode == undefined || Parameters.mode == null) return
    if (Parameters.mode === "2d") {
      // window.mapmodel = "2D"
      //  window.dragcount = 1;
      window.sceneView.goTo({
        heading: 0,
        tilt: 0,
      });
      //  ['basemap_as_baimodel', 'basemap_zw_baimodel', 'basemap_Air_readmodel'].forEach(element => {
      //        const layer = window.map.findLayerById(element);
      //        if(layer==null) return;
      //         layer.visible =false;
      //         layer.listMode ='hide';
      //  })
    } else if (Parameters.mode === "3d") {
      // window.mapmodel = "3D";
      //  window.dragcount = 2;
      window.sceneView.goTo({
        heading: 0.1,
        tilt: 60,
      });
      // let mapvh=[];
      //  window.map.basemap.baseLayers.items.forEach(function (item) {
      //     if (item.id === "basemap_air") {
      //      if (item.visible)
      //       mapvh=[
      //         ['model_white_as', false, 'hide'],
      //         ['model_white_zw', false, 'hide'],
      //         ['model_air_real', true, 'show']
      //       ]
      //     } else if (item.id === "basemap_zw") {
      //       if (item.visible)
      //       mapvh = [
      //         ['model_white_as', false, 'hide'],
      //         ['model_white_zw', true, 'show'],
      //         ['model_air_real', false, 'hide']
      //       ]

      //     } else if (item.id === "basemap_as") {
      //       if (item.visible)
      //        mapvh = [
      //          ['model_white_as', true, 'show'],
      //          ['model_white_zw', false, 'hide'],
      //          ['model_air_real', false, 'hide']
      //        ]
      //     }
      //  })
      // mapvh.forEach(element => {
      //   let layer = window.map.findLayerById(element[0]);
      //   if (layer == null || layer == undefined) return
      //   layer.visible = element[1];
      //   layer.listMode = element[2];
      // })
    }
  },

  undergroundmode(Parameters) {
    if (Parameters.isopen == undefined || Parameters.isopen == null) return
    if (Parameters.isopen) {
      window.sceneView.map.ground.surfaceColor = '#fff';
      window.sceneView.map.ground.opacity = 0;
    } else {
      window.sceneView.map.ground.surfaceColor = null;
      window.sceneView.map.ground.opacity = 1;
    }
  },

  async bimmodelslice(Parameters) {
    if (Parameters.layername == undefined || Parameters.layername == null) return
    window.excludedLayers = [];
    if (window.sliceWidget) {
      window.sceneView.ui.remove(window.sliceWidget);
      window.sliceWidget.destroy();
      window.sliceWidget = null;
    }
    const buildingLayer = window.sceneView.map.findLayerById(Parameters.layername)
    if (buildingLayer == null) return;
    const [Slice] = await load(["esri/widgets/Slice"]);
    if (Parameters.openSlice) {
      const buildingLayer = window.map.findLayerById(Parameters.layername)
      buildingLayer.when(function () {
        buildingLayer.allSublayers.forEach(function (layer) {
          // modelName is standard accross all BuildingSceneLayer,
          // use it to identify a certain layer
          switch (layer.modelName) {
            // Because of performance reasons, the Full Model view is
            // by default set to false. In this scene the Full Model should be visible.
            case "FullModel":
              layer.visible = true;
              break;
            case "Overview":
            case "Roofs":
            case "Walls":
            case "Rooms":
              layer.visible = true;
              break;
            // Extract the layers that should not be hidden by the slice widget
            case "Doors":
              window.excludedLayers.push(layer);
            case "StructuralColumns":
            case "Floors":
            case "Furniture":
            case "CurtainWallPanels":
              window.excludedLayers.push(layer);
              break;
            default:
              layer.visible = true;
          }
        })

        window.sliceWidget = new Slice({
          view: window.sceneView
        });
        window.sliceWidget.viewModel.newSlice();
        window.sliceWidget.viewModel.excludedLayers.addMany(window.excludedLayers);
        window.sceneView.ui.add(window.sliceWidget, "bottom-leading");
      })
    } else {

      buildingLayer.visible = false
      if (window.sliceWidget != null) {
        window.sliceWidget.destroy();
        window.sliceWidget = null;
      }
    }
  },
  async bimmodelfilter(Parameters) {
    if (Parameters.layername == undefined || Parameters.layername == null) return
    if (window.bimfilterWidget) {
      window.sceneView.ui.remove(window.bimfilterWidget);
      window.bimfilterWidget = null;
    }
    const buildingLayer = window.sceneView.map.findLayerById(Parameters.layername)
    if (buildingLayer == null) return;
    if (Parameters.openfilter) {
      const [BuildingSencelayerFilter] = await load(["esri/widgets/BuildingSencelayerFilter"]);
      window.bimfilterWidget = new BuildingSencelayerFilter({
        view: window.sceneView,
        layerid: Parameters.layername
      });
      window.sceneView.ui.add(window.bimfilterWidget, "bottom-leading");
    } else {
      buildingLayer.visible = false
      if (window.bimfilterWidget != null) {
        window.sceneView.ui.remove(window.bimfilterWidget);
        window.bimfilterWidget = null;
      }
    }
  },
  togglemouseevent(Parameters) {
    window.disableMouseEvent = Parameters.disableMouseEvent == undefined || Parameters.disableMouseEvent == null || Parameters.disableMouseEvent == true ? true : false;
    if (window.disableMouseEvent) {
      window.draghandler = window.sceneView.on('drag', function (event) {
        event.stopPropagation();
      });

      window.doubleclickhandler = window.sceneView.on('double-click', function (event) {
        event.stopPropagation();
      });

      window.mousewheelhandler = window.sceneView.on('mouse-wheel', function (event) {
        event.stopPropagation();
      });

    } else {
      if (window.draghandler != null)
        window.draghandler.remove();
      if (window.doubleclickhandler != null)
        window.doubleclickhandler.remove();
      if (window.mousewheelhandler != null)
        window.mousewheelhandler.remove();
    }
  },

  async togglemodelHight(Parameters) {
    const [Query] = await load(["esri/tasks/support/Query"]);
    if (Parameters.ishightlight == undefined || Parameters.ishightlight == null || Parameters.ishightlight == true) {
      if (Parameters.modelids == null || Parameters.modelids == undefined) return
      let modellayer = window.map.findLayerById(Parameters.layername)
      window.sceneView.whenLayerView(modellayer).then(function (modellayerview) {
        // if (window.modelhighlight)
        //   window.modelhighlight.remove();
        // window.modelhighlight = modellayerview.highlight(Parameters.modelids);
        if (Parameters.field == undefined) {
          var queryExtent = new Query({
            objectIds: Parameters.modelids
          });
          modellayerview.queryExtent(queryExtent).then(function (result) {
            if (result.extent == null) { return }
            window.sceneView.goTo({
              center: result.extent.expand(7).center,
              zoom: 12,
              tilt: 80,
              heading: window.sceneView.camera.heading
            }, {
              speedFactor: 0.5
            }).then(function () {
              modellayer.renderer = SencelayerRenderer.model_hightrenderer(Parameters.modelids, Parameters.layername, 'objectid')
            });
          });
        } else {
          let querystr = Parameters.field + "= '" + Parameters.modelids[0] + "'";
          Parameters.modelids.map(function (item, key, ary) {
            if (key > 0) {
              querystr += " OR " + Parameters.field + "= '" + item + "'"
            }
          });
          var queryfilter = new Query();
          queryfilter.where = querystr
          modellayer.outFields = ["*"];
          modellayerview.queryExtent(queryfilter).then(function (result) {
            if (result.extent == null) { return }
            modellayer.renderer = SencelayerRenderer.model_hightrenderer(Parameters.modelids, Parameters.layername, Parameters.field)
            // window.sceneView.goTo({
            //   center: result.extent.expand(7).center,
            //   zoom: 12,
            //   tilt: 80,
            //   heading: window.sceneView.camera.heading
            // }, {
            //   speedFactor: 0.5
            // }
            // ).then(function () {
            //   modellayer.renderer = SencelayerRenderer.model_hightrenderer(Parameters.modelids, Parameters.layername, Parameters.field)
            // });
          });
        }
      })
    } else {
      if (window.modelhighlight)
        window.modelhighlight.remove();
      let modellayer
      if (Parameters.layername === "basemap_as_baimodel") {
        modellayer = window.map.findLayerById(Parameters.layername)
        modellayer.renderer = maprenderer.as_baimodel
      } else if (Parameters.layername === "basemap_zw_baimodel") {
        modellayer = window.map.findLayerById(Parameters.layername)
        modellayer.renderer = maprenderer.zw_baimodel
      } else {
        modellayer = window.map.findLayerById(Parameters.layername)
        modellayer.renderer = null;
      }
    }
  },



  async togglemodelSurHight(Parameters) {
    const [Query] = await load(["esri/tasks/support/Query"]);
    if (Parameters.ishightlight == undefined || Parameters.ishightlight == null || Parameters.ishightlight == true) {
      if (Parameters.modelids == null || Parameters.modelids == undefined) return
      let modellayer = window.map.findLayerById(Parameters.layername)
      window.sceneView.whenLayerView(modellayer).then(function (modellayerview) {
        if (Parameters.field == undefined) {
          var queryExtent = new Query({
            objectIds: Parameters.modelids
          });
          modellayerview.queryExtent(queryExtent).then(function (result) {
            //暂时取消拉近功能
            // window.sceneView.goTo(result.extent.expand(7), {
            //   speedFactor: 0.5
            // });
            if (window.modelhighlight) {
              window.modelhighlight.remove();
            }
            window.modelhighlight = modellayerview.highlight(Parameters.modelids);
          });
        } else {
          let querystr = Parameters.field + "= '" + Parameters.modelids[0] + "'";
          Parameters.modelids.map(function (item, key, ary) {
            if (key > 0) {
              querystr += " OR " + Parameters.field + "= '" + item + "'"
            }
          });
          var queryfilter = new Query();
          queryfilter.where = querystr
          modellayer.outFields = ["*"];
          modellayerview.queryExtent(queryfilter).then(function (result) {
            if (result.extent == null) { return }
            // window.sceneView.goTo(result.extent.expand(7), {
            //   speedFactor: 0.5
            // });
            // if (window.modelhighlight) {
            //   window.modelhighlight.remove();
            // }
            // window.modelhighlight = modellayerview.highlight(Parameters.modelids);
          });
        }
      })

    } else {
      if (window.modelhighlight) {
        window.modelhighlight.remove();
      }
    }
  },


  async hightlightclear() {
    const hightlightLayer = window.map.findLayerById("XH_Graphiclayer");
    if (hightlightLayer != null || hightlightLayer != undefined)
      hightlightLayer.removeAll();
  },

  //接口未开放
  removeLayerbyName(Parameters) {
    const Layer = window.map.findLayerById(Parameters.layerName);
    if (Layer != null || Layer != undefined) {
      window.map.remove(Layer)
    } else {
      Message({
        message: "图层" + Parameters.layerName + "不存在",
        type: 'warning',
        duration: 2 * 1000
      })
    }
  },

  ////接口未开放
  async addLayerbyName(Parameters) {
    const [Legend] = await load(["esri/widgets/Legend"]);
    let Layer = window.map.findLayerById(Parameters.layerName);
    if (Layer === null || Layer === undefined)
      Layer = window[Parameters.layerName];
    window.map.add(Layer)
    if (Parameters.sublayers != null && Parameters.sublayers != undefined)
      Layer.sublayers = Parameters.sublayers;
    Layer.visible = true;
    Layer.listMode = "show";

    let legendlayer = window.map.findLayerById(Parameters.layerName + "_legend");
    if (legendlayer === null || legendlayer === undefined)
      legendlayer = window[Parameters.layerName + "_legend"];

    if (Parameters.sublayers != null && Parameters.sublayers != undefined)
      legendlayer.sublayers = Parameters.sublayers;
    legendlayer.visible = true;
    legendlayer.opacity = 0.5;
    legendlayer.listMode = "hide";

    if (window.legend != null) window.sceneView.ui.remove(window.legend);
    window.legend = new Legend({
      view: window.sceneView,
      layerInfos: [{
        layer: legendlayer,
      }]
    });
    window.sceneView.ui.add(window.legend, "bottom-right");
  }
};
export default mapoperation
